package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备表Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IoTDAClient client;

    /**
     * 查询设备表
     * 
     * @param id 设备表主键
     * @return 设备表
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备表列表
     * 
     * @param device 设备表
     * @return 设备表
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备表
     * 
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }



    /**
     * 批量删除设备表
     * 
     * @param ids 需要删除的设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }


    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        //设置参数
        listProductsRequest.setLimit(50);
        // 发起请求
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if (response.getHttpStatusCode()!=200) {
            throw new RuntimeException("同步产品列表失败");
        }
        //存储到redis
        List<ProductSummary> products = response.getProducts();
        redisTemplate.opsForValue().set(Constants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(products));
    }
    /**
     * 查询产品列表
     */
    @Override
    public List<ProductVo> allProduct() {
     //从redis中获取数据
        String result = (String) redisTemplate.opsForValue().get(Constants.IOT_ALL_PRODUCT_LIST);
       //判断数据是否为空
        if (StringUtils.isEmpty(result)) {
            return Collections.emptyList();
        }
        return JSONUtil.toList(result, ProductVo.class);
    }
     /**
     * 注册设备
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //判断设备名称是否为空
        long count = count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if(count > 0){
            throw new RuntimeException("设备名称已存在");
        }
        //判断同一位置是否绑定同一产品
        count = count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(deviceDto.getPhysicalLocationType() != null, Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
        );
        if (count > 0) {
            throw new RuntimeException("同一位置只能绑定同一产品");
        }
        //判断设备标识是否存在
        count = count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId()));
        if (count > 0) {
            throw new RuntimeException("设备标识已存在");
        }
        //注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body=new AddDevice();
        body.setNodeId(deviceDto.getNodeId());
        body.setDeviceName(deviceDto.getDeviceName());
        body.setProductId( deviceDto.getProductKey());
        String secret= UUID.randomUUID().toString().replaceAll("-", "");
        AuthInfo authInfo = new AuthInfo();
        authInfo.setSecret(secret);
        body.setAuthInfo(authInfo);
        request.setBody(body);
        AddDeviceResponse addDeviceResponse = client.addDevice(request);
        if (addDeviceResponse.getHttpStatusCode() != 201) {
            throw new RuntimeException("设备注册失败");
        }
        //保存设备信息
        Device device= BeanUtil.toBean(deviceDto, Device.class);
        device.setBindingLocation(String.valueOf(deviceDto.getBindingLocation()));
        device.setIotId(addDeviceResponse.getDeviceId());
        device.setSecret(secret);
        this.save( device);
    }
   /**
     * 查询设备详情
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //查询本地数据
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty( device)) {
            throw new RuntimeException("设备不存在");
        }
        //查询iot信息
        ShowDeviceRequest request=new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse showDeviceResponse = client.showDevice(request);
        if (showDeviceResponse.getHttpStatusCode() != 200){
            throw new RuntimeException("设备详情查询失败");
        }
        DeviceDetailVo bean = BeanUtil.toBean(device, DeviceDetailVo.class);
        bean.setDeviceStatus(showDeviceResponse.getStatus());
        String activeTimeStr = showDeviceResponse.getActiveTime();
        if(StringUtils.isNotEmpty(activeTimeStr)) {
            // 日期时区转换
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            // 日期时区转换
            bean.setActiveTime(DateTimeZoneConverter.utcToShanghai(activeTime));
        }
        return bean;
    }
    /**
     * 查询设备上报数据
     */
    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request=new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse showDeviceShadowResponse = client.showDeviceShadow(request);
        if (showDeviceShadowResponse.getHttpStatusCode() != 200){
            throw new RuntimeException("设备详情查询失败");
        }
        List<DeviceShadowData> shadow = showDeviceShadowResponse.getShadow();
        if (CollUtil.isEmpty(shadow)){
            return Collections.emptyList();
        }
        DeviceShadowProperties reported = shadow.get(0).getReported();
        String eventTime = reported.getEventTime();
        // 把数据转换为JSONObject(map)，方便处理
        JSONObject jsonObject = JSONUtil.parseObj(reported.getProperties());
        List<Map<String, Object>> list = new ArrayList<>();
        //转化时间类型
        final LocalDateTime time=LocalDateTimeUtil.parse(eventTime,"yyyyMMdd'T'HHmmss'Z'");
        LocalDateTime localDateTime = DateTimeZoneConverter.utcToShanghai(time);
        jsonObject.forEach((key, value) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId",  key);
            map.put("value", value);
            map.put("eventTime",localDateTime);
            list.add(map);
        });
        return list;
    }

    /**
     * 修改设备表
     *
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        //从iot修改设备名称
        UpdateDeviceRequest request=new UpdateDeviceRequest();
        request.setDeviceId(device.getIotId());
        UpdateDevice body=new UpdateDevice();
        body.setDeviceName(device.getDeviceName());
        request.setBody(body);
        UpdateDeviceResponse updateDeviceResponse = client.updateDevice(request);
        if (updateDeviceResponse.getHttpStatusCode() != 200) {
            throw new RuntimeException("设备修改失败");
        }
        //从数据库

        return updateById(device) ? 1 : 0;
    }
    /**
     * 删除设备表信息
     *
     * @param iotId 设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(String iotId)
    {
        DeleteDeviceRequest request =new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        DeleteDeviceResponse deleteDeviceResponse = client.deleteDevice(request);
        if (deleteDeviceResponse.getHttpStatusCode() != 204){
            throw new RuntimeException("设备删除失败");
        }
        boolean remove = this.remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        return remove?1:0;
    }
    /**
     * 查询产品详情
     */
    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        if(productKey==null){
            throw new RuntimeException("产品Key不能为空");
        }
        //查询iot设备数据
        ShowProductRequest request=new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse showProductResponse = client.showProduct(request);
        if (showProductResponse.getHttpStatusCode() != 200){
            throw new RuntimeException("产品详情查询失败");
        }
        List<ServiceCapability> serviceCapabilities = showProductResponse.getServiceCapabilities();
        if (CollUtil.isNotEmpty(serviceCapabilities)) {
            return serviceCapabilities;
        }
        return serviceCapabilities;
    }
}
